package com.xh.bussiness.tiku.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.jingyou.bean.request.JYPaperQueryRequest;
import com.xh.bussiness.jingyou.bean.request.JYPaperSaveRequest;
import com.xh.bussiness.jingyou.bean.request.JYSmartPaperSaveRequest;
import com.xh.bussiness.jingyou.service.IJYPaperService;
import com.xh.bussiness.teachbook.util.PaperUtils;
import com.xh.bussiness.tiku.bean.dto.PaperDto;
import com.xh.bussiness.tiku.bean.request.*;
import com.xh.bussiness.tiku.model.Paper;
import com.xh.bussiness.tiku.service.IPaperService;
import com.xh.core.annotation.ExcludeLoginTokenIntercept;
import com.xh.core.bean.AjaxResult;
import com.xh.core.bean.XhPage;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.util.FileUtils;
import com.xh.core.util.StringUtils;
import com.xh.core.util.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Collections;

/*
 * @Author daiwei
 * @Description
 * @Date 2019/3/14 15:18
 **/
@Api(tags = "题库-试卷接口")
@RestController
@RequestMapping("/tiku/paper")
public class PaperController {

    @Autowired
    private IPaperService paperService;
    @Autowired
    private IJYPaperService jypaperService;

    @PostMapping("/queryPaperMoudle")
    @ApiOperation(value = "查询试卷模块列表", notes = "查询试卷模块列表")
    public AjaxResult queryPaperMoudle() {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", paperService.queryPaperModule());
    }

    @PostMapping("/queryPaperPage")
    @ApiOperation(value = "试卷分页查询", notes = "试卷分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bean", value = "试卷信息", required = true, dataType = "PaperQueryRequest"),
    })
    public AjaxResult queryPaperPage(HttpServletRequest request, XhPage page, PaperQueryRequest bean) {
        bean.setCreatorId(request.getHeader("userId"));
        if(page.getTotal()!=0){
            page.setTotal(0);
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", paperService.queryPaperPage(page, bean));
    }

    /**
     * 查询同步练习
     * @author 赵文博
     * @date 2021/5/27 10:10
     * @param page
     * @param bean
     * @return com.xh.core.bean.AjaxResult
     **/
    @PostMapping("/queryExercise")
    public AjaxResult queryExercise(XhPage<Paper> page, PaperQueryRequest bean) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", paperService.queryExercise(page, bean));
    }

    /**
     * 查询入门测
     * @param page
     * @param bean
     * @return com.xh.core.bean.AjaxResult
     **/
    @PostMapping("/queryEntranceTest")
    public AjaxResult queryEntranceTest(XhPage<Paper> page, PaperQueryRequest bean) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", paperService.queryEntranceTest(page, bean));
    }

    @PostMapping("/addPaper")
    @Transactional
    @ApiOperation(value = "试卷保存", notes = "试卷保存")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bean", value = "试卷信息", required = true, dataType = "PaperSaveRequest"),
    })
    public AjaxResult addPaper(HttpServletRequest request,@RequestBody PaperSaveRequest bean) {
        PaperDto paper = paperService.addPaper(request,bean);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, paper);
    }

    @PostMapping("/batchSavePaper")
    @Transactional
    @ApiOperation(value = "批量试卷保存", notes = "批量试卷保存")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bean", value = "试卷信息", required = true, dataType = "PaperSaveRequest"),
    })
    public AjaxResult batchSavePaper(@RequestBody PaperBatchSaveRequest bean) {
        paperService.batchSavePaper(bean);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    @PostMapping("/getPaper")
    @ApiOperation(value = "查询试卷", notes = "查询试卷")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "试卷ID", required = true, dataType = "String"),
    })
    public AjaxResult getPaper(String id) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, paperService.getPaper(id));
    }

    @PostMapping("/deletePaper")
    @ApiOperation(value = "试卷删除", notes = "试试卷删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "试卷ID", required = true, dataType = "String"),
    })
    public AjaxResult deletePaper(String id) {
        paperService.deletePaper(id);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "");
    }
    /**
     * 审核试卷
     *
     * @param id           试卷id
     * @param checkStatus  审核状态 0未审核 1不通过 2通过
     * @param rejectReason 驳回原因
     * @param rejectDesc   驳回描述
     * @return
     */
    @PostMapping("/checkPaper")
    @ApiOperation(value = "审核试卷", notes = "审核试卷")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "试卷ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "checkStatus", value = "审核状态 0未审核 1不通过 2通过", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "wrongType", value = "错误类型 12345", dataType = "Integer"),
            @ApiImplicitParam(name = "reason", value = "错误原因", dataType = "String"),
    })
    public AjaxResult checkPaper(String id, Integer checkStatus, String rejectReason, String rejectDesc) {
        paperService.checkPaper(id, checkStatus, rejectReason, rejectDesc);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "");
    }

    //todo 自动填充nickname

    /**
     * 查询审核列表
     *
     * @param request
     * @return
     */
    public XhPage<Paper> queryCheckPaper(XhPage<Paper> page, PaperRequest request) {
        return paperService.queryCheckPaper(page, request);
    }

    /**
     * 查询审核列表
     *
     * @param bean
     * @return
     * @throws Exception
     */
    @PostMapping("/smartPaper")
    @ApiOperation(value = "菁优智能组卷", notes = "菁优智能组卷")
    public AjaxResult smartPaper(@RequestBody JYSmartPaperSaveRequest bean) throws Exception {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, jypaperService.smartPaper(bean));
    }

    /**
     * 选题组卷
     *
     * @param bean
     * @return
     * @throws Exception
     */
    @PostMapping("/jy/submitPaper")
    @ApiOperation(value = "选题组卷", notes = "选题组卷")
    public AjaxResult submitPaper(@RequestBody JYPaperSaveRequest bean) throws Exception {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, jypaperService.selectQuestionPaper(bean));
    }

    /**
     * 选题组卷
     *
     * @param bean
     * @return
     * @throws Exception
     */
    @PostMapping("/jy/getPaper")
    @ApiOperation(value = "选题组卷", notes = "选题组卷")
    public AjaxResult getPaper(JYPaperQueryRequest bean) throws Exception {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, jypaperService.queryPaper(bean));
    }

    /**
     * 选题组卷
     *
     * @param bean
     * @return
     * @throws Exception
     */
    @GetMapping("/downPaper")
    @ExcludeLoginTokenIntercept
    @ApiOperation(value = "下载试卷", notes = "下载试卷")
    public void downPaper(String paperId, Integer type, String fileType, String templateId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (null == type) {
            //默认学生卷
            type = 2;
        }
        PaperDto paperDto = paperService.getPaper(paperId);
        if (paperDto != null) {
            StringBuffer url = request.getRequestURL();
            String rootPath = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
            String filePath = PaperUtils.exportPaper(paperDto, type, templateId, request,fileType);
            System.out.println(filePath);
            Paper paper = paperService.getById(paperId);
            paper.setDownloadCount(paper.getDownloadCount() + 1);
            paperService.update(paper);
            FileUtils.downloadLocalFile(paperDto.getTitle(), filePath, response);
        }
    }

    /**
     * 更新下载次数
     *
     * @param bean
     * @return
     * @throws Exception
     */
    @PostMapping("/countDownloadPaper")
    @ApiOperation(value = "更新下载次数", notes = "更新下载次数")
    public AjaxResult downPaper(String paperId) throws Exception {
        if (StringUtils.isEmpty(paperId)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        Paper paper = paperService.getById(paperId);
        if (paper != null) {
            paper.setDownloadCount(paper.getDownloadCount() + 1);
            paperService.update(paper);
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, paper);
    }

    /**
     * 选题组卷
     *
     * @param bean
     * @return
     * @throws Exception
     */
    @PostMapping("/jy/queryByPage")
    @ApiOperation(value = "分页查询", notes = "分页查询")
    public AjaxResult queryByPage(XhPage<PaperDto> page, JYPaperQueryRequest bean) throws Exception {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, jypaperService.queryByPaparm(page, bean));
    }

    @ExcludeLoginTokenIntercept
    @PostMapping("/intellectPaper")
    @ApiOperation(value = "智能组卷", notes = "智能组卷")
    public AjaxResult intellectPaper(@RequestBody PaperQuestionRequest bean) throws Exception {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, paperService.intellectPaper(bean));
    }

    /**
     * 选题组卷
     *
     * @param bean
     * @return
     * @throws Exception
     */
    @GetMapping("/downPdfPaper")
    @ExcludeLoginTokenIntercept
    @ApiOperation(value = "下载试卷", notes = "下载试卷")
    public void downPdfPaper(String paperId, Integer type, String templateId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (null == type) {
            //默认学生卷
            type = 2;
        }
        PaperDto paperDto = paperService.getPaper(paperId);
        if (paperDto != null) {
            StringBuffer url = request.getRequestURL();
            String rootPath = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
            String filePath = PaperUtils.exportPaperNew(paperDto, type, templateId, request,"pdf");
            System.out.println(filePath);
            Paper paper = paperService.getById(paperId);
            paper.setDownloadCount(paper.getDownloadCount() + 1);
            paperService.update(paper);
            FileUtils.downloadLocalFile(paperDto.getTitle(), filePath, response);
        }
    }

    @PostMapping("/addBlankRow")
    @ApiOperation(value = "新增空行", notes = "新增空行")
    public AjaxResult addBlankRow(String paperId, String questionId, Integer blankRowCount) throws Exception {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, paperService.addBlankRow(paperId, questionId, blankRowCount));
    }

    @PostMapping("/copyPaper")
    @ApiOperation(value = "复制试卷，用于一对一备课进门考，作业", notes = "复制试卷，用于一对一备课进门考，作业")
    public AjaxResult copyPaper(String paperId) throws Exception {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "",paperService.copyPaper(paperId));
    }


    /**
     * 修改试卷属性
     * @author 赵文博
     * @date 2021/5/24 14:31
     * @param paper
     * @return com.xh.core.bean.AjaxResult
     **/
    @PostMapping("/updatePaper")
    public AjaxResult updatePaper(@RequestBody Paper paper){
        boolean flag = paperService.updatePaper(paper);
        return flag ? new AjaxResult(AjaxResultConstant.Result.SUCCESS)
                : new AjaxResult(AjaxResultConstant.Result.ERROR);
    }

    /**
     * 查询学科网导入的试卷
     * @author 赵文博
     * @date 2021/6/2 15:04
     * @param page
     * @return com.xh.core.bean.XhPage
     **/
    @PostMapping("/queryXKWPaper")
    public AjaxResult queryXKWPaper(XhPage page,Paper paper){
        QueryWrapper<Paper> qw = new QueryWrapper<>();
        qw.eq("subject_id",paper.getSubjectId());
        qw.eq("source_from",5);
        qw.orderByDesc("modify_time");
        XhPage page1 = (XhPage)paperService.selectPage(page,qw,PaperDto.class);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,page1);
    }
}
